package cn.shyouchi.wuguanjia.android.http;

import java.io.File;
import java.util.concurrent.TimeUnit;

import cn.shyouchi.wuguanjia.android.api.youchi.YouChiService;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by movier on 16/8/31.
 */
public class HttpMethods {
    //    public static final String BASE_URL = "http://10.0.2.2:8000/api/";
//    public static final String BASE_URL = "http://192.168.1.224:8000/api/";
//    public static final String BASE_URL = "http://192.168.100.102:8000/api/";
//    public static final String BASE_URL = "http://121.42.213.83/api/";
    public static final String BASE_URL = "http://118.178.88.132:8000/api/";

    public static final String HANVON_BASE_URL = "http://api.hanvon.com/";

    private static final int DEFAULT_TIMEOUT = 5;

    private static final String TAG = "HttpMethods";

    private Retrofit retrofit;
    private Retrofit hanvonRetrofit;
    private YouChiService movieService;
    private YouChiService hanvonService;

    //构造方法私有
    private HttpMethods() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();

        movieService = retrofit.create(YouChiService.class);

        hanvonRetrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(HANVON_BASE_URL)
                .build();
        hanvonService = hanvonRetrofit.create(YouChiService.class);
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final HttpMethods INSTANCE = new HttpMethods();
    }

    //获取单例
    public static HttpMethods getInstance() {
        return SingletonHolder.INSTANCE;
    }


//
//    public void fetchSmsCode(Subscriber<String> subscriber, String telephone) {
//        movieService.fetchSmsCode(telephone)
//                .map(new HttpResultFunc<String>())
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber);
//    }

    public void register(Subscriber<String> subscriber,
                         String username,
                         String password,
                         String name,
                         String gender,
                         String birthday,
                         String address,
                         String number,
                         String publisher,
                         String validate,
                         int height,
                         String graduate,
                         String telephone,
                         String livingAddress,
                         String emergecyContact,
                         String industry,
                         String skill,
                         String channel,
                         File file,
                         File negative,
                         File headImage) {


        RequestBody usernameBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), username);
        RequestBody passwordBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), password);
        RequestBody nameBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), name);
        RequestBody genderBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), gender);
        RequestBody birthdayBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), birthday);
        RequestBody addressBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), address);
        RequestBody numberBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), number);
        RequestBody publisherBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), publisher);
        RequestBody validateBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), validate);
        RequestBody heightBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), height + "");
        RequestBody graduateBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), graduate);
        RequestBody telephoneBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), telephone);
        RequestBody livingAddressBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), livingAddress);
        RequestBody emergencyBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), emergecyContact);
        RequestBody industryBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), industry);
        RequestBody skillBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), skill);
        RequestBody channelBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), channel);

        // create RequestBody instance from file
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);

        // MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("id_card_positive", file.getName(), requestFile);

        RequestBody negativeRequestBody =
                RequestBody.create(MediaType.parse("multipart/form-data"), negative);
        MultipartBody.Part negativeBody =
                MultipartBody.Part.createFormData("id_card_negative", negative.getName(), negativeRequestBody);

        RequestBody headRequestBody =
                RequestBody.create(MediaType.parse("multipart/form-data"), headImage);
        MultipartBody.Part headBody =
                MultipartBody.Part.createFormData("id_card_head_image", headImage.getName(), headRequestBody);

//        movieService.register(usernameBody,
//                passwordBody,
//                nameBody,
//                genderBody,
//                birthdayBody,
//                addressBody,
//                numberBody,
//                publisherBody,
//                validateBody,
//                heightBody,
//                graduateBody,
//                telephoneBody,
//                livingAddressBody,
//                emergencyBody,
//                industryBody,
//                skillBody,
//                channelBody,
//                body,
//                negativeBody,
//                headBody)
//                .map(new HttpResultFunc<String>())
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber);
    }

    public void propertyRegister(Subscriber<String> subscriber, String username, String password,
                                 String name, String company, String position, String email) {
        movieService.propertyRegister(username, password, name, company, position, email)
                .map(new HttpResultFunc<String>())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

//    public void login(Subscriber<LoginMod> subscriber, String username, String password) {
//        movieService.login(username, password)
//                .map(new HttpResultFunc<LoginMod>())
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber);
//    }

//    public void identifyIDCard(Subscriber<IdCardEntity> subscriber, IdCardRequest idCardRequest) {
//        hanvonService.identidyIdCard(idCardRequest)
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber);
//    }

    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T> Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    private class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {
        @Override
        public T call(HttpResult<T> httpResult) {
//            if (httpResult.getResultCode() != 0) {
//                throw new ApiException(httpResult.getResultCode());
//            }
            return httpResult.getData();
        }
    }
}
